package org.subside.thread;


import org.springframework.context.annotation.Bean;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.ThreadPoolExecutor;


/**
 * @Author : zhangbo
 * @data : 2024/5/8
 * @description :线程池工厂工具
 */
public class ThreadPoolFactory {
    /**
     * 生成固定大小的线程池
     * @param threadName 线程名称
     * @return 线程池
     */

    /**
     * 获取当前运行机器的可用CPU核心数
     */
    private final static int POLLER_THREAD_COUNT = Runtime.getRuntime().availableProcessors() * 2;

    @Bean
    public TaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 核心线程数
        executor.setCorePoolSize(POLLER_THREAD_COUNT);
        // 最大线程数
        executor.setMaxPoolSize(POLLER_THREAD_COUNT * 8);
        // 空闲线程最大存活时间，默认60秒
        executor.setKeepAliveSeconds(0);
        // 队列最大容量
        executor.setQueueCapacity(256);
        // 线程的名称前缀
        executor.setThreadNamePrefix("taskExecutor-thread-");
        // 拒绝策略-交由调用者的线程执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 等待所有任务结束后再关闭线程池，默认false
        executor.setWaitForTasksToCompleteOnShutdown(true);
        // 等待所有任务结束最长等待时间，默认0毫秒
        executor.setAwaitTerminationSeconds(0);
        // 执行初始化
        executor.initialize();
        return executor;
    }
}
